package com.landtool.lanbase.shipping;

import com.fasterxml.jackson.databind.util.PrimitiveArrayBuilder;
import com.landtool.lanbase.config.SysConfig;
import com.landtool.lanbase.constant.CacheConsts;
import com.landtool.lanbase.database.entity.BdDataFusion;
import com.landtool.lanbase.database.entity.TargetAreaManagement;
import com.landtool.lanbase.database.entity.TgMidCountry;
import com.landtool.lanbase.database.entity.WarnBlack;
import com.landtool.lanbase.database.service.BdDataFusionService;
import com.landtool.lanbase.database.service.TargetAreaManagementService;
import com.landtool.lanbase.database.service.TgMidCountryService;
import com.landtool.lanbase.database.service.WarnBlackService;
import com.landtool.lanbase.elasticsearch.ElasticServer;
import com.landtool.lanbase.entity.ShipEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务，程序入口
 */
@Controller
public class TimeTask {

    /**
     * 注入配置
     */
    @Autowired
    private SysConfig sysConfig;

    @Autowired
    private TgMidCountryService tgMidCountryService;

    @Autowired
    private ElasticServer elasticServer;

    @Autowired
    private BdDataFusionService bdDataFusionService;

    @Autowired
    private FormatProcess formatProcess;

    @Autowired
    private ShippingService shippingService;

    @Autowired
    private GetShipData getShipData;

    @Autowired
    private RedisTemplate <String,Object> redisTemplate;

    @Autowired
    private PushService pushService;

    @Resource
    private WarnBlackService warnBlackService;

    @Resource
    private TargetAreaManagementService targetAreaManagementService;

    /**
     * 是否是第一次获取参数
     */
    private static Boolean firstObtain = true;

    private static int count = 0;


    /**
     * 定时获取数据
     *
     * @return
     */
//    @Scheduled(fixedDelay = 10 * 1000)
    public void get() {
        setCache();
        GetCountry();
        String type = "rest";
        GetShipData getShipData = new GetShipData();
        //这个方法只走rest接口的方式
        if (type.equals(CacheConsts.openType)) {
            //原始数据
            String result = getShipData.getRestTypeData();
            if (!"".equals(result)) {
                restPullAndSave(result);
            }

        }
    }

    @PostConstruct()
    public void init() {
        //需要开启一个新的线程来执行netty server 服务器
        new Thread(new Runnable() {
            @Override
            public void run() {
                setCache();
                String type = "zmq";
                if(type.equals(CacheConsts.openType)){
                    GetCountry();
                    getShipData.getZmqTypeData();
                }
            }
        }).start();
    }

    /**
     * 查询北斗数据
     */
    @Scheduled(fixedDelay = 120 * 1000)
    public void getRecentList() {
        List <BdDataFusion> list = bdDataFusionService.GetRecentList();
        HashMap <String, BdDataFusion> hmap = new HashMap <String, BdDataFusion>();
        for (int i = 0; i < list.size(); i++) {
            hmap.put(String.valueOf(list.get(i).getTargetId()), list.get(i));
        }
        CacheConsts.RecentList=hmap;
    }



    /**
     * rest数据操作
     *
     * @param result 原始数据
     */
    public void restPullAndSave(String result) {
        //数据处理
        formatProcess.getNewArray(result);
        //船只数据对比，分析，修改
        HashMap <String, List <ShipEntity>> map = shippingService.analyzeShipping();
        //数据前端推送
        pushService.pushShipData(map);
        //数据保存在es中
        if (count == sysConfig.getPushNum()) {
            //保存es数据库
            elasticServer.bulkShipDates();
            //推送所有数据 数据分析服务
            pushService.pushAllShipData();
            elasticServer.tagetChangesSave();
            count = 0;
        } else {
            count++;
        }
    }

    /**
     * 设置全局缓存
     */
    public void setCache() {
        if (firstObtain) {
            CacheConsts.openType = sysConfig.getOpenType();
            CacheConsts.openProvince = sysConfig.getOpenProvince();
            CacheConsts.isLogin = sysConfig.getIsLogin();
            firstObtain = false;
        }
    }

    /**
     * 获取国籍表
     */
    public void GetCountry() {
        TgMidCountry tgMidCountry = new TgMidCountry();
        List <TgMidCountry> tgMidCountryList = tgMidCountryService.queryAll(tgMidCountry);
        HashMap <String, TgMidCountry> hmap = new HashMap <String, TgMidCountry>();
        for (int i = 0; i < tgMidCountryList.size(); i++) {
            hmap.put(tgMidCountryList.get(i).getMid(), tgMidCountryList.get(i));
        }
        //将map存入redis
        CacheConsts.Country=hmap;
    }

    /**
     * 黑名单数据
     */

    @Scheduled(fixedDelay = 300 * 1000)
    public void getWarnBlackList(){
        WarnBlack warnBlack=new WarnBlack();
        List<WarnBlack> list =warnBlackService.queryAll(warnBlack);
        HashMap <String, WarnBlack> hmap = new HashMap <String, WarnBlack>();
        for (int i = 0; i < list.size(); i++) {
            hmap.put(list.get(i).getMmsi(),list.get(i));
        }

        //将处理好的 字段提交到redis
        String warnBlackKey = CacheConsts.openProvince + "_WarnBlack";
        if(!redisTemplate.hasKey(warnBlackKey)){
            redisTemplate.opsForHash().putAll(warnBlackKey,hmap);
            redisTemplate.expire(warnBlackKey, 500, TimeUnit.SECONDS);
        }
    }

    /**
     * 获取目标区域
     */
    @Scheduled(fixedDelay = 300 * 1000)
    public void getTargetAreaList(){
        TargetAreaManagement targetAreaManagement=new TargetAreaManagement();
        List<TargetAreaManagement> list =targetAreaManagementService.queryAll(targetAreaManagement);

        //将处理好的 字段提交到redis
        String areaKey = CacheConsts.openProvince + "_targetArea";
        redisTemplate.opsForValue().set(areaKey, list);
        redisTemplate.expire(areaKey, 500, TimeUnit.SECONDS);
    }


    /**
     * 获取项目根路径
     *
     * @return
     */
    private static String getResourceBasePath() {
        // 获取跟目录
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            // nothing to do
        }
        if (path == null || !path.exists()) {
            path = new File("");
        }

        String pathStr = path.getAbsolutePath();
        // 如果是在eclipse中运行，则和target同级目录,如果是jar部署到服务器，则默认和jar包同级
        pathStr = pathStr.replace("\\target\\classes", "");
        return pathStr;
    }
}
